const AJAX = getApp().ajax,
      $wx = getApp().$wx,
      getColor = getApp().globalData.getColor;

Page({
  data: {
    getColor: {},
    showBtnStatus: 1,
    showAuthorize: false
  },

  onLoad(){
    this.getShopConfig();
  },

  //获取用户信息
  getUserInfo(e){
    let _this = this, user_info = e.detail;
    _this.isAuthorization('userInfo', (status) => {

      if (status) {
        wx.setStorageSync('userInfo', user_info);        
        _this.login(user_info.userInfo);
      } else {
        $wx.showToast('请选打开授权！');

        _this.setData({
          showBtnStatus: 2
        });
      }
    });
   
  },

  //打开授权 
  openSetting(e){
    let _this = this;
    _this.isAuthorization('userInfo', (status) => {
      if (status) {
        _this.setData({
          showBtnStatus: 1
        });
      }
    });
  },

  /**
   * 登录
   * @param code
   * @param user_nickname
   * @param avatar
   * */ 
  login(userInfo){
    let _this = this;  
    wx.login({
      success: loginRes => {
        wx.showLoading({
          title: '登录中...',
          mask: true
        });

        AJAX.login({
          code: loginRes.code,
          user_nickname: userInfo.nickName,
          avatar: userInfo.avatarUrl
        }, (status, data, msg) => {
          wx.hideLoading();
          if (status) {
            wx.redirectTo({
              url: '/pages/tab-bar/shop/shop',
              success(){
                wx.setStorageSync('token', data.token);
              }
            });
          } else {
            $wx.showToast(msg);
          }
        });
      }
    });
  },
  
  /*商店配置*/
  getShopConfig(){
    let _this = this, token = wx.getStorageSync('token');
    wx.showNavigationBarLoading();

    AJAX.getShopConfig({}, (status, data, msg) => {
      wx.hideNavigationBarLoading();

      if(status){
        wx.setNavigationBarTitle({
          title: data.shop_name,
        });
        
        wx.setStorageSync('shopConfig', data);
        _this.setData({
          getColor: getColor(),
          shopConfig: data
        });
        $wx.setNavColor(getColor().val); 
        
        if (token){
          setTimeout(callBack=>{
            wx.redirectTo({
              url: '/pages/tab-bar/shop/shop'
            });
          },1000);
          
        }else{
          _this.setData({
            showAuthorize: true
          });
        }
      }else{
        $wx.showToast(msg);
      }
    });
  },

  /*是否授权*/
  isAuthorization(type, callback) {
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.' + type]) {
          callback(true);
        } else {
          callback(false);
        }
      }
    })
  }
});